import React, { useRef, useState } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import { Button, Image, Switch, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { getGoods, isOn, isRecommend } from '@/services/goods' 
import CreateOrEdit from './components/CreateOrEdit'


export default function Index() {

  const actionRef = useRef()

  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editId, setEditId] = useState(undefined)

  // 获取商品列表数据 （初始化、搜索时刷新）
  const getData = async (params) => {
    // console.log(params)
    const response = await getGoods(params)
    // console.log(response)
    return {
      data: response.data,
      // success 请返回 true，不然 table 会停止解析数据，即使有数据
      success: true,
      // 不传会使用 data 的长度，如果是分页一定要传
      total: response.meta.pagination.total
    }
  }

  // 上架和下架商品
  const handleIsOn = async (goodId) => {
    const response = await isOn(goodId)
    if(response.status === undefined) message.success('操作成功!')
  }
  // 推荐和不推荐商品
  const handleIsRecommend = async (goodId) => {
    const response = await isRecommend(goodId)
    if(response.status === undefined) message.success('操作成功!')
  }

  // 控制模态框显示与隐藏
  const isShowModal = (show, goodId = undefined) => {
    setIsModalVisible(show)
    setEditId(goodId)
  }

  const columns = [
    {
      title: '商品图',
      dataIndex: 'cover_url',
      hideInSearch: true,
      render: (_, record) => <Image 
        width={64} src={record.cover_url}
      />
    },
    {
      title: '标题',
      dataIndex: 'title'
    },
    {
      title: '价格',
      dataIndex: 'price',
      hideInSearch: true
    },
    {
      title: '库存',
      dataIndex: 'stock',
      hideInSearch: true
    },
    {
      title: '销量',
      dataIndex: 'sales',
      hideInSearch: true
    },
    {
      title: '是否上架',
      dataIndex: 'is_on',
      render: (_, record) => <Switch
        checkedChildren="已上架" unCheckedChildren="未上架" 
        defaultChecked={record.is_on === 1}
        onChange={ async () => handleIsOn(record.id) }
      />,
      valueType: 'radioButton',
      valueEnum: {
        1: { text: '已上架' },
        0: { text: '未上架' }
      }
    },
    {
      title: '是否推荐',
      dataIndex: 'is_recommend',
      render: (_, record) => <Switch
        checkedChildren="已推荐" unCheckedChildren="未推荐" 
        defaultChecked={record.is_recommend === 1}
        onChange={ async () => handleIsRecommend(record.id) }
      />,
      valueType: 'radioButton',
      valueEnum: {
        1: { text: '已推荐' },
        0: { text: '未推荐' }
      }
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      hideInSearch: true
    },
    {
      title: '操作',
      hideInSearch: true,
      render: (_, record) => <a onClick={() => isShowModal(true, record.id)}>编辑</a>
    }
  ]

  return (
    <PageContainer>
      {/* 高级表格 */}
      <ProTable
        columns={columns}
        actionRef={actionRef}
        // request={ async (params = {}, sort, filter) => getUsers(params) }
        request={ async (params = {}, sort, filter) => getData(params) }
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="商品列表"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary" onClick={ () => isShowModal(true) }>
            新建
          </Button>
        ]}
      />

      {/* 模态框 */}
      {
        // 配合 hook 模拟声明周期函数 componentDidMount， 重写卸载和挂载、与 骨架屏 配合使用
        isModalVisible ? 
          <CreateOrEdit editId={editId} isModalVisible={isModalVisible} isShowModal={isShowModal} actionRef={actionRef} /> 
        : ''
      }
    </PageContainer>
  )
}
